package it.koutifaris.travianmap.view.serversettingsview;

import it.koutifaris.travianmap.R;
import it.koutifaris.travianmap.context.HasApplicationContex;
import it.koutifaris.travianmap.dal.TravianServerSettingsService;
import it.koutifaris.travianmap.view.serversettingsview.MapUrlVerifier.MapUrlResutlHandler;

import java.net.URL;

import android.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;

class OnOkHandler extends HasApplicationContex implements MapUrlResutlHandler {

	private static final String TAG = OnOkHandler.class.getName();
	private final ServerViewController controller;

	public OnOkHandler(ServerViewController controller) {
		this.controller = controller;
	}

	@Override
	public void onValidResource(URL mapUrl) {
		TravianServerSettingsService settingsService = getTravianMapContext().getServerServiceFactory().travianServerSettingsService();

		settingsService.saveSettings(controller.getModel());
		settingsService.close();

		Toast.makeText(getActivity(), R.string.server_settings_saved, Toast.LENGTH_SHORT).show();
		controller.getView().hideProgressBar();

		ServerViewController.finishAndReturnToRootActivity();
	}

	@Override
	public void onResourceNotPresent(URL url) {
		showDialogAndHideProgressBar(
				R.string.server_unreachable_server_title,
				url + " " + getActivity().getResources().getString(R.string.server_unreachable_url));
	}

	@Override
	public void onMalformedUrl(String malformedUrl) {
		showDialogAndHideProgressBar(
				R.string.server_invalid_server_title,
				malformedUrl + " " + getActivity().getResources().getString(R.string.server_invalid_server_msg));
	}

	@Override
	public void onException(Throwable e) {
		showDialogAndHideProgressBar(
				R.string.server_unexpeted_error,
				getActivity().getResources().getString(R.string.server_unexpeted_error_msg));

		Log.e(TAG, "Error while saving server settings: " + e);
	}

	private void showDialogAndHideProgressBar(int titleId, String msg) {
		createDialog(titleId, msg).show();
		controller.getView().hideProgressBar();
	}

	private AlertDialog createDialog(int titleId, String msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

		return builder
				.setTitle(titleId)
				.setMessage(msg)
				.create();
	}

}
